package cn.le.crawler;

import cn.le.annotation.CrawlerName;
import cn.le.enums.EnumCrawler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author le
 * @Date 2020/4/14 14:30
 * @Version 0.1
 **/
@Component
@Configuration
public class CrawlerFactory {

    @Autowired
    private ApplicationContext applicationContext;

    private static final Map<EnumCrawler,Crawler> CrawlerMap = new HashMap<>();

    public static Crawler  getCrawler(EnumCrawler crawler){
        return CrawlerMap.get(crawler);
    }

    @Bean
    public void initCrawler(){
        List<Crawler> list = new ArrayList<>(applicationContext.getBeansOfType(Crawler.class).values());
        list.forEach(crawler -> {
            EnumCrawler enumCrawler = crawler.getClass().getAnnotation(CrawlerName.class).value();
            CrawlerMap.put(enumCrawler,crawler);
        });
    }
}
